//
//  EntryTabBarController.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/6.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import JMessage
import ESTabBarController_swift
import RxSwift

class EntryTabBarController: ESTabBarController {

    var datas: [JMSGConversation] = []
    let authManager = AuthManager.share
    
    var v1: UINavigationController?
    var v2: UINavigationController?
    
    let disposeBag = DisposeBag()
    
    let versionVM = VersionViewModel.share
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.delegate = self
        v1 = (UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "HomeTableNavigationController") as! UINavigationController)
        v2 = (UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "PersonalNavigationController") as!  UINavigationController)
        v1?.tabBarItem = ESTabBarItem.init(BarItemBasicContentView(), image: UIImage.init(named: "wineGlass"), selectedImage: UIImage.init(named: "wineGlass_1"))
        v2?.tabBarItem = ESTabBarItem.init(BarItemBasicContentView(), image: UIImage.init(named: "me"), selectedImage: UIImage.init(named: "me_1"))
        
        checkUnread()
        
        self.shouldHijackHandler = {
            tabbarController, viewController, index in
            if index == 1 && !self.authManager.hasLogined() {
                return true
            }
            return false
        }
        
        self.didHijackHandler = {
            [unowned self] tabbarController, viewController, index in
            self.showLoginPage()
        }
        
        self.tabBar.isTranslucent = false
        self.viewControllers = [v1!, v2!]
        
        JMessage.add(self, with: nil)
        
        //getConversations()
        //NotificationCenter.default.addObserver(self, selector: #selector(getConversations), name: NSNotification.Name(rawValue: kUpdateConversation), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(readAllMsgs), name: hasReadAllMsgs, object: nil)
        
        checkVersion()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func checkVersion() {
        versionVM.getVersion().subscribe(onNext: { version in
            LATESTVERSION = Double(version)!            
        })
        .addDisposableTo(disposeBag)
    }
    
    func checkUnread() {
        if let db = SystemMessageDB.getShareInstance() {
            let count = db.unreadCount()
            if count > 0 {
                hasUnreadMsg = true
                self.v2?.tabBarItem.badgeValue = ""
                NotificationCenter.default.post(name: hasNewUnReadMsg, object: nil)
            } else {
                hasUnreadMsg = false
                self.v2?.tabBarItem.badgeValue = nil
            }
        }
    }
    
    func readAllMsgs() {
        hasUnreadMsg = false
        self.v2?.tabBarItem.badgeValue = nil
    }
    
    func getConversations() {
        JMSGConversation.allConversations { [unowned self] (result, error) in
            guard let conversatios = result else {
                return
            }
            self.datas = conversatios as! [JMSGConversation]
            for data in self.datas {                
                let messages = data.messageArrayFromNewest(withOffset: nil, limit: nil)
                //print("獲取會話！")
                for msg in messages {                    
                    let set = (msg.content?.dictionaryWithValues(forKeys: ["text"]))!
                    var orderId: Int = 0
                    var role: String = ""
                    if let extra = msg.content?.extras {
                        if let o_idString: String = extra["orderId"] as? String {
                            guard let o_id: Int = Int(o_idString) else {
                                print("error message")
                                return
                            }
                            guard let role_temp: String = extra["role"] as? String else {
                                print("error message")
                                return
                            }
                            orderId = o_id
                            role = role_temp
                        }
                        print("orderId: \(orderId);  role: \(role)")
                    }
                    if let db = SystemMessageDB.getShareInstance() {
                        let currentDate = Date()
                        let dateformatter = DateFormatter()
                        dateformatter.dateFormat = "YYYY.MM.dd"
                        let dateString = dateformatter.string(from: currentDate)
                        let msgBody = set["text"] as! String
                        //print("message: \(msgBody)  \(dateString)")
                        let message = SystemMessage(id: 0, message: msgBody, has_read: 0, orderId: orderId, role: role, received_time: dateString)
                        db.insertData(message)
                    }
                }
                
                data.deleteAllMessages()
                data.clearUnreadCount()
                self.checkUnread()
            }
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension EntryTabBarController: JMessageDelegate {
    
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        //print(message.fromUser.nickname)
        //print(message.content!)
        //v2?.tabBarItem.badgeValue = ""
//        print("接受消息！！")
        getConversations()
    }
    
    func onConversationChanged(_ conversation: JMSGConversation!) {
        getConversations()
    }
    
    func onGroupInfoChanged(_ group: JMSGGroup!) {
        getConversations()
    }
    
    func onSyncRoamingMessageConversation(_ conversation: JMSGConversation!) {
//        print("活動！")
        getConversations()
    }
    
    func onSyncOfflineMessageConversation(_ conversation: JMSGConversation!, offlineMessages: [JMSGMessage]!) {
//        print("離線消息！")
        getConversations()
    }
    
    func onReceive(_ retractEvent: JMSGMessageRetractEvent!) {
//        print("活動2！")
        getConversations()
    }
    
}
